/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.montoroTurismo.beans;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.montoroTurismo.dao.AccesoBD;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author ajdiaz
 */
public class OffersBean {

    /**
     * Creates a new instance of OffersBean
     */
    private int id;
    private String titulo;
    private String dateEnd;
    private String descripcion;
    private String path;
    private String username;
    private final HttpServletRequest httpServletRequest;
    private final FacesContext faceContext;
    private OffersBean offertable;
    private UploadedFile file;

    public OffersBean() {
        faceContext = FacesContext.getCurrentInstance();
        httpServletRequest = (HttpServletRequest) faceContext.getExternalContext().getRequest();
        if (("modificar").equals(httpServletRequest.getSession().getAttribute("accion"))) {
            offertable = (OffersBean) httpServletRequest.getSession().getAttribute("offerTableForm");
            this.setId(offertable.getId());
            this.setDateEnd(offertable.getDateEnd());
            this.setTitulo(offertable.getTitulo());
            this.setDescripcion(offertable.getDescripcion());

        }
    }

    public OffersBean(int id, String titulo, String dateEnd, String descripcion) {
        faceContext = FacesContext.getCurrentInstance();
        httpServletRequest = (HttpServletRequest) faceContext.getExternalContext().getRequest();
        this.id = id;
        this.titulo = titulo;
        this.dateEnd = dateEnd;
        this.descripcion = descripcion;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitulo() {
        return titulo;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getDateEnd() {
        return dateEnd;
    }

    public void setDateEnd(String dateEnd) {
        this.dateEnd = dateEnd;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public String saveOffer() {
        String succes = "";
        FacesMessage msg = null;
        try {
            AccesoBD db = new AccesoBD();
            username = httpServletRequest.getSession().getAttribute("sessionUsuario").toString();
            if (("modificar").equals(httpServletRequest.getSession().getAttribute("accion"))) {
                httpServletRequest.getSession().setAttribute("accion", "");
                if (fileUpload()) {
                    db.updateOffer(this, username);
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Oferta modificada!", "La ofertase modifico correctamente!");
                    succes = "succes";
                    db.close();
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                }
            } else {
                if (fileUpload()) {
                    db.insertOffer(this, username);
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Oferta Lanzada!", "La oferta se lanzo correctamente");
                    succes = "succes";
                    db.close();
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(OffersBean.class.getName()).log(Level.SEVERE, null, ex);
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error!", "Ha habido un error");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
        return succes;
    }

    public boolean fileUpload() throws IOException {
        FacesMessage msg = null;
        if (file.getFileName().equals("")) {
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Inserta una imagen", "Por favor insertar una imagen menos de 5 Mb");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {


            String ruta = "http://ec2-54-72-200-10.eu-west-1.compute.amazonaws.com:8080/";
            java.text.SimpleDateFormat formato = new java.text.SimpleDateFormat("ddMMyy");
            int posicionPunto = file.getFileName().indexOf(".");
            String nombreImagen = file.getFileName().substring(0, posicionPunto);
            String extension = file.getFileName().substring(posicionPunto);
            nombreImagen = nombreImagen + formato.format(new java.util.Date());
            nombreImagen = username + "-" + nombreImagen + extension;
            this.setPath(ruta + nombreImagen);
            File finalFile = new File("/var/www/" + nombreImagen);

            InputStream is = file.getInputstream();
            OutputStream out = new FileOutputStream(finalFile);
            byte buf[] = new byte[1024];
            int len;
            while ((len = is.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            is.close();
            out.close();
            return true;
        }
    }
}
